﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Mime;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.IO;
using System.Net;


namespace Common
{
	public class WebHelper
	{

		public static async Task<string> HttpPost(string url, string data, Dictionary<string, string> headers, string contentType = "application/x-www-form-urlencoded")
		{
			var httpRequestMessage = new HttpRequestMessage();
			httpRequestMessage.Method = HttpMethod.Post;
			httpRequestMessage.RequestUri = new Uri(url);
			//httpRequestMessage.Content = new StringContent(string.IsNullOrEmpty(data)?"":data, Encoding.Default, string.IsNullOrEmpty(contentType) ? "application/x-www-form-urlencoded" : contentType);
			
			
			httpRequestMessage.Content = new StringContent(string.IsNullOrEmpty(data)?"":data, Encoding.Default, string.IsNullOrEmpty(contentType) ? "application/x-www-form-urlencoded" : contentType);
			if (headers != null && headers.Count > 0)
			{
				foreach (var item in headers)
				{
					httpRequestMessage.Headers.Add(item.Key, item.Value);
				}

			}
			
			HttpClient httpClient = HttpClientFactory.Create();
			HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);

			if (httpResponseMessage.IsSuccessStatusCode && httpResponseMessage.Content != null)
			{
                try
                {
					return httpResponseMessage.Content.ReadAsStringAsync().Result;
				}
                catch (Exception ex)
                {
					var isoContent = "";
					using (var sr = new StreamReader(httpResponseMessage.Content.ReadAsStreamAsync().Result, Encoding.GetEncoding("iso-8859-1")))
					{
						isoContent = sr.ReadToEnd();
					}
					string num = EncodeBase64(isoContent);
					string str = DecodeBase64(num);
					return isoContent;
				}
			}
			else
			{
				return string.Empty;
			}
		}
		public static async Task<string> HttpPost32(string url, string data, Dictionary<string, string> headers, string contentType = "application/x-www-form-urlencoded")
		{
			try
            {


                var httpRequestMessage = new HttpRequestMessage();
                httpRequestMessage.Method = HttpMethod.Post;
                httpRequestMessage.RequestUri = new Uri(url);
                httpRequestMessage.Content = new StringContent(string.IsNullOrEmpty(data) ? "" : data, Encoding.UTF8, string.IsNullOrEmpty(contentType) ? "application/x-www-form-urlencoded" : contentType);
                if (headers != null && headers.Count > 0)
                {
                    foreach (var item in headers)
                    {
                        httpRequestMessage.Headers.Add(item.Key, item.Value);
                    }

                }

                HttpClient httpClient = HttpClientFactory.Create();
                HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);

                if (httpResponseMessage.IsSuccessStatusCode && httpResponseMessage.Content != null)
                {

                    var isoContent = "";
                    using (var sr = new StreamReader(httpResponseMessage.Content.ReadAsStreamAsync().Result, Encoding.GetEncoding("UTF-8")))//iso-8859-1
					{
                        isoContent = sr.ReadToEnd();
                    }
                    return isoContent;
                }
                else
                {
                    return string.Empty;
                }
            }
            catch (Exception ex)
            {
				return $"error:{ex.Message}";
            }
        }

        public static string httpRepost(string PostUrl, Dictionary<string, object> reqParams)
		{
			string url = PostUrl;
			WebRequest request = WebRequest.Create(url);
			request.Method = "POST";

			try
			{
				string postdata = reqParams.ToString();
				byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postdata);
				request.ContentType = "application/json";
				request.ContentLength = bytes.Length;
				Stream sendStream = request.GetRequestStream();
				sendStream.Write(bytes, 0, bytes.Length);
				sendStream.Close();
				WebResponse response = request.GetResponse();
				string OrderQuantity = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
				return OrderQuantity;
			}
			catch (Exception ex)
			{
				//Logger.Error("QRCode httpRepost:", "http—post错误" + ex.Message, ex);
				throw ex;
			}
		}


		public static string DecodeBase64(string code)
        {
			string sdecode = "";
			byte[] sconverted = Convert.FromBase64String(code);
            try
            {
				sdecode = ASCIIEncoding.GetEncoding("GD2312").GetString(sconverted);
            }
            catch (Exception)
            {
				sdecode = code;
			}
			return sdecode;
        }


		public static string EncodeBase64(string code)
        {
			string sdecode = "";
			byte[] sconverted = Encoding.Default.GetBytes(code);
			try
			{
				sdecode = Convert.ToBase64String(sconverted);
			}
			catch (Exception)
			{
				sdecode = code;
			}
			return sdecode;
		}

		public static string LanChange(string str)
        {
			Encoding utf8;
			Encoding gb3212;
			utf8 = Encoding.GetEncoding("UTF-8");
			gb3212 = Encoding.GetEncoding("GB2312");
			byte[] gb = gb3212.GetBytes(str);
			gb = Encoding.Convert(gb3212,utf8,gb);
			return utf8.GetString(gb);
        }

	}
}
